package com.hzxgs.tracelogstarter.trace;

import com.hzxgs.tracelogstarter.properties.TraceProperties;
import com.hzxgs.tracelogstarter.util.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
@ConditionalOnClass(value = { GlobalFilter.class })
@Order(TraceUtils.FILTER_ORDER)
@Slf4j
public class GatewayTraceFilter implements GlobalFilter {

    @Resource
    private TraceProperties traceProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (!traceProperties.getEnable()) {
            return chain.filter(exchange);
        }
        try {
            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders headers = request.getHeaders();
            String traceId = headers.getFirst(TraceUtils.TRACE_ID_HEADER);
            // 请求头中traceId为空
            if (StringUtils.isBlank(traceId)) {
                TraceUtils.addTrace();
            } else {
                String spanId = headers.getFirst(TraceUtils.SPAN_ID_HEADER);
                TraceUtils.putTrace(traceId, spanId);
            }

            ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                    .headers(h -> {
                        h.add(TraceUtils.TRACE_ID_HEADER, TraceUtils.getTraceId());
                        h.add(TraceUtils.SPAN_ID_HEADER, TraceUtils.getNextSpanId());
                    })
                    .build();
            ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
            log.info("网关收到请求，增加traceId: {}. spanId: {}", TraceUtils.getTraceId(), TraceUtils.getSpanId());
            return chain.filter(build);
        } catch (Exception e) {
            log.info("网关设置链路追踪失败！");
            e.printStackTrace();
        } finally {
            TraceUtils.removeTrace();
        }
        return chain.filter(exchange);
    }
}
